import request from '@/utils/request'

// 登录API（表单提交，适配后端接口）
export const login = async (credentials) => {
  try {
    const formData = new URLSearchParams()
    formData.append('phone', credentials.phone) // 后端使用phone字段
    formData.append('password', credentials.password)

    const response = await request.post('/auth/login', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })

    // 后端返回JWT Token字符串
    if (response) {
      localStorage.setItem('token', response)
      // 登录成功后获取用户信息
      try {
        const userInfo = await getCurrentUser()
        localStorage.setItem('user', JSON.stringify(userInfo))
        return { token: response, user: userInfo }
      } catch (error) {
        console.warn('获取用户信息失败:', error)
        return { token: response, user: null }
      }
    }

    return response
  } catch (error) {
    throw error
  }
}

// 注册API（表单提交，适配后端接口）
export const register = async (userData) => {
  try {
    const formData = new URLSearchParams()
    formData.append('phone', userData.phone)
    formData.append('password', userData.password)
    if (userData.name) formData.append('name', userData.name)
    if (userData.code) formData.append('code', userData.code)

    const response = await request.post('/auth/register', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })

    // 注册成功后自动登录
    if (response) {
      localStorage.setItem('token', response)
      // 注册成功后获取用户信息
      try {
        const userInfo = await getCurrentUser()
        localStorage.setItem('user', JSON.stringify(userInfo))
        return { token: response, user: userInfo }
      } catch (error) {
        console.warn('获取用户信息失败:', error)
        return { token: response, user: null }
      }
    }

    return response
  } catch (error) {
    throw error
  }
}

// 发送注册验证码（URL 表单参数风格）
export const sendCode = async (phone) => {
  try {
    const formData = new URLSearchParams()
    formData.append('phone', phone)

    const response = await request.post('/auth/sendCode', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 登出API
export const logout = async () => {
  try {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    // 可选：await request.post('/auth/logout')
    return { success: true }
  } catch (error) {
    throw error
  }
}

// 获取当前用户信息（使用新接口 /auth/user/info）
export const getCurrentUser = async () => {
  try {
    const response = await request.get('/auth/user/info')
    return response
  } catch (error) {
    throw error
  }
}

// 更新用户信息
export const updateUserInfo = async (userData) => {
  try {
    const formData = new URLSearchParams()
    if (userData.name) formData.append('name', userData.name)
    if (userData.avatar) formData.append('avatar', userData.avatar)

    const response = await request.post('/auth/user/update', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 修改密码
export const changePassword = async (passwordData) => {
  try {
    const formData = new URLSearchParams()
    formData.append('oldPassword', passwordData.oldPassword)
    formData.append('newPassword', passwordData.newPassword)

    const response = await request.post('/auth/user/changePassword', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 修改用户名
export const changeName = async (newName) => {
  try {
    const formData = new URLSearchParams()
    formData.append('newName', newName)

    const response = await request.post('/auth/user/changeName', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 上传文件
export const uploadFile = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await request.post('/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 更新用户头像
export const updateAvatar = async (avatarUrl) => {
  try {
    const formData = new URLSearchParams()
    formData.append('avatarUrl', avatarUrl)

    const response = await request.patch('/auth/updateAvatar', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    return response
  } catch (error) {
    throw error
  }
}

// 刷新token
export const refreshToken = async () => {
  try {
    const response = await request.post('/auth/refresh')
    if (response.token) localStorage.setItem('token', response.token)
    return response
  } catch (error) {
    throw error
  }
}

// 忘记密码
export const forgotPassword = async (phone) => {
  try {
    const response = await request.post('/auth/forgot-password', { phone })
    return response
  } catch (error) {
    throw error
  }
}

// 重置密码
export const resetPassword = async (token, newPassword) => {
  try {
    const response = await request.post('/auth/reset-password', { token, password: newPassword })
    return response
  } catch (error) {
    throw error
  }
}

export default request
